import { defineComponent, onMounted } from "vue";
window.$paramsArr = [];
export default defineComponent({
  props: {
    index: Number,
    option: Object,
    searchData : Array
  },
  setup(props, { emit }) {
    const _that = props.option
    onMounted(()=>{
      getProps()
    })
    let originArr = []
    function getProps() {
      let _that = props.option
      window.$paramsArr.push({}) // 初始化
      // 根据情况赋默认值
      if (props.option.type == 'daterange') {
          window.$paramsArr[props.index] = {
          [_that.prop1]: _that.defaultDate[0] ? _that.defaultDate[0] + ' 00:00:00' : '',
          [_that.prop2]: _that.defaultDate[1] ? _that.defaultDate[1] + ' 23:59:59' : ''
        }
      } else {
        window.$paramsArr[props.index][_that.prop] = _that.value || ''
      }
        originArr = JSON.parse(JSON.stringify(window.$paramsArr));
    }
    function valChange(val, prop, index) {
      // 用index定位数组位置，prop定位对象位置
        // if (_that.datalist) {
        //   let obj = list.find(i => i.name == _that.value)
        //   window.$paramsArr[index][prop] = obj ? obj.id : -1
        // }else{
        //   window.$paramsArr[index][prop] = val ? _that.value : ''
        // }
         window.$paramsArr[index][prop] = val ? _that.value : ''
    }
    function getTimerange(val, p1, p2, index) {
      if(val){
      // 格式化
      // let dptVal = JSON.parse(JSON.stringify(val))
        let sTime = setDateFormat(val[0].$d) + ' 00:00:00'
        let eTime = setDateFormat(val[1].$d) + ' 23:59:59';
        window.$paramsArr[index][p1] = sTime
        window.$paramsArr[index][p2] = eTime
      }else{
        window.$paramsArr[index][p1] = ''
        window.$paramsArr[index][p2] = ''
        props.searchData[index].defaultDate = ['开始日期','结束日期']
      }
    }
    function setDateFormat(originVal) {
        const dt = new Date(originVal)
        const y = dt.getFullYear()
        const m = (dt.getMonth() + 1 + '').padStart(2, '0')
        const d = (dt.getDate() + '').padStart(2, '0')
        return `${y}-${m}-${d}`
    }
    function handleChange(val, prop, index) {
      window.$paramsArr[index][prop] = val ? _that.value : ''
    }
    function filterSelect(input, option) {
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    }
    function filterInput(input, option) {
      return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    }
    let options = []
    function saveOptios(){
      options = JSON.parse(localStorage.getItem(`_option_${_that.label}`)) || []
      // 去重并删除
      if (_that.value && options.length != 0) {
        options.forEach((item,index) =>{
          if(item.value == _that.value){
            options.splice(index,1)
          }
        })
      }
      // 空值不存入
      if(_that.value) options.unshift({value:_that.value})
      _that.options = options.slice(0, 10) // 限制存10条
    }
    function doSearch(){
      emit('doSearch')
      // 存历史记录：键名不能相同
      for(let i = 0 ; i < props.searchData.length ; i++){
        if (props.searchData[i].type == 'input-complete'){
          localStorage.setItem(`&option_${props.searchData[i].label}`, JSON.stringify(props.searchData[i].options))
        }
      }
    }
    function doClear() {
      let arr = originArr.slice(0, originArr.length - 1) // 去掉多余
      for (let i = 0; i < props.searchData.length - 2; i++) {
        if ((props.searchData[i].type == "daterange")) { // 时间范围重置
          props.searchData[i].value = ''
        }else{
            for (let key in arr[i]) {
              props.searchData[i].value = arr[i][key]
            }
        }
      }
      emit('doClear', arr)
    }
    let btnStyle = {
        padding: '10px',
        position: "absolute",
        right: "25px",
        // top: "24px"
      }
    let spanStyle = {
        float: 'left',
        textAlign: 'right',
        fontSize: '13px',
        paddingRight: '10px',
        width: '90px',
      }
    switch (_that.type){
      case 'daterange':
        return ()=>(
          <div>
            <span style = {{...spanStyle,..._that.labelStyle}}>{_that.label}</span>
            <a-range-picker
              onChange = {(val) => {getTimerange(val,_that.prop1,_that.prop2,props.index)}}
              style = {{width : "220px", ..._that.style}}
              v-model:value = { _that.value}
              format = "YYYY-MM-DD"
              size = {_that.size || 'middle'}
              placeholder = { _that.defaultDate}
              />
          </div>
       )
       case 'input':
        return () => (
          <div>
            <span style = {{...spanStyle,..._that.labelStyle}}>{_that.label}</span>
            <a-input 
                
                style = {{width : "220px",..._that.style}}
                onChange = {(val) => {valChange(val, _that.prop, props.index)}}
                placeholder = {_that.placeholder || '请输入'}
                v-model:value = {_that.value}
                size = {_that.size || 'middle'}
                allowClear
            ></a-input>
          </div>
        )
      case 'select':
        return ()=>(
          <div>
            <span style = {{...spanStyle,..._that.labelStyle}}>{_that.label}</span>
            <a-select 
                onChange = {(val) => {valChange(val, _that.prop, props.index)}}
                style = {{width : "220px", ..._that.style} }
                v-model:value = {_that.value}
                show-search = {false || _that.showSearch}
                size = {_that.size || 'middle'}
                placeholder = { _that.placeholder|| "请选择"}
                allowClear
                >{
                    _that.options.map(item =>{
                        return ( <a-select-option
                        value = {item.value}
                        >{item.label}</a-select-option>)
                    })
                }
              </a-select>
          </div>
        )
      case 'select-search':
        return ()=>(
          <div>
            <span style={{...spanStyle,..._that.labelStyle}}>{_that.label}</span>
            <a-select 
                onChange = {(val) => {handleChange(val, _that.prop, props.index)}}
                style = {{width : "220px", ..._that.style} }
                v-model:value = {_that.value}
                options = {_that.options}
                filter-option = {filterSelect}
                show-search
                size = {_that.size || 'middle'}
                placeholder = { _that.placeholder|| "请选择"}
                allowClear
                >
              </a-select>
          </div>
        )
      case 'input-complete':
        return ()=>(
          <div>
            <span style={{...spanStyle,..._that.labelStyle}}>{_that.label}</span>
            < a-auto-complete
                ref='completeInput'
                onChange = {(val) => {handleChange(val, _that.prop, props.index)}}
                onBlur = {()=> {saveOptios()}}
                style = {{width : "220px", ..._that.style} }
                v-model:value = {_that.value}
                options = {JSON.parse(localStorage.getItem(`&option_${_that.label}`)) || []}
                filter-option = {filterInput}
                size = {_that.size || 'middle'}
                placeholder = { _that.placeholder|| "请输入"}
                
                />
          </div>
        )
      case 'search-btn':
        return()=>(
          <a-button 
              type = "primary"
              style= {{ ...btnStyle,top: "24px",..._that.style}}
              onClick = {() => {doSearch()}}
              size = {_that.size || "middle"}
              >查 询
          </a-button>
        )
      case 'clear-btn':
        return()=>(
          <a-button 
              style= {{ ...btnStyle,right: "95px",..._that.style}}
              onClick = {() => {doClear()}}
              size = {_that.size || "middle"}
              >重 置
          </a-button>
        )
    }
}
})